<template>
  <div class="app-container">
    <div :class="['filter-container','open']" style="height:55px!important">

      <!-- 展开状态下的筛选框 -->
      <el-form ref="form" :inline="true" :model="form" label-width="80px">
        <el-form-item label="模板名称">
          <el-input v-model.trim="form.name" placeholder="" clearable />
        </el-form-item>
        <el-form-item label="模板类型">
          <el-select v-model="form.type" placeholder="" clearable >
            <el-option v-for="item in importanceOptions" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
            <el-date-picker
              v-model="form.startTime"
              type="date"
              placeholder="选择开始日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions1"
              >
            </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间">
            <el-date-picker
              v-model="form.endTime"
              type="date"
              placeholder="选择结束日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions2"
              >
            </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" label-width="50px">
          <el-select v-model="form.status" placeholder="" clearable>
            <el-option v-for="item in sortOptions" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item>
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
            查询
            </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit-outline" @click="handleReset">
            重置
            </el-button>
        </el-form-item>
      </el-form>
    </div>
     <el-button class="filter-item" type="primary" style="margin-bottom: 15px;" @click="handleCreate">
        新增
     </el-button>
      <el-row :gutter="12" style="height:calc(100vh - 260px);overflow-y:scroll">
        <el-col :span="6" v-for="item in list" :key="item.id">
            <el-card shadow="always" style="cursor: pointer;margin-bottom:10px">
                <div @click="handleLook(item)">
                    <p class="oneStyle">{{item.name}}<span class="twoStyle">({{item.type==1?"单体贫血模型":item.type==2?"SOA贫血模型":"微服务贫血模型"}})</span></p>
                    <p class="threeStyle" style="display: flex;justify-content: space-between;">
                      <span>创建人：{{item.createUserName}}</span>
                      <span>{{item.create_Time}}</span>
                    </p>
                    <div style="display: flex;justify-content: space-between;">
                      <span class="threeStyle">项目骨架模板：{{item.templateProjectName}}</span>
                      <p class="icons_Style" :style="{color:item.status==1?'#67c23a':'#f56c6c',background:item.status==1?'rgb(232, 255, 234)':'rgb(255, 236, 232)'}"><i style="margin-right: 3px;" :class="item.status==1?'el-icon-success':'el-icon-error'"></i>{{item.status==1?'已上线':'未上线'}}</p>
                    </div>
                    <div style="text-align: right;">
                      <el-button type="primary" @click.stop="handleEdit(item)">编辑</el-button>
                      <el-button type="danger" @click.stop="handleDelete(item)">删除</el-button>
                    </div>
                </div>
            </el-card>
        </el-col>
      </el-row>
    <pagination v-show="total>0" :total="total" :page.sync="form.page" :limit.sync="form.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="30%" v-if="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="110px"
      >
         <el-form-item label="模板名称" prop="name">
          <el-input v-model.trim="temp.name" placeholder="" clearable :disabled="isDisabled" />
        </el-form-item>
        <el-form-item label="模板类型" prop="type">
          <el-select v-model="temp.type" placeholder="" clearable :disabled="isDisabled">
            <el-option v-for="item in importanceOptions" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
       <el-form-item label="代码模板分组" prop="codeGroupId">
          <el-select v-model="temp.codeGroupId" placeholder="" clearable :disabled="isDisabled">
            <el-option v-for="item in templateLists" :key="item.id" :label="item.groupName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="模板描述">
            <el-input type="textarea" v-model="temp.description" placeholder="" clearable :disabled="isDisabled"></el-input>
        </el-form-item>
        <el-form-item label="状态">
            <el-radio-group v-model="temp.status" :disabled="isDisabled">
            <el-radio :label="1">已上线</el-radio>
            <el-radio :label="2">未上线</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="项目骨架模板" prop="templateProjectId">
          <el-select v-model="temp.templateProjectId" class="filter-item" placeholder="" clearable :disabled="isDisabled" >
            <el-option v-for="item in skeletonTemplate" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-show="!isDisabled">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { projectTemplatefindPage,codeGrouplist,projectTemplatesave,projectTemplateupdate,projectTemplatedelete,projectlist } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination 分页组件

const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'LayoutTable',
  components: { Pagination },
  directives: { waves }, // 指令
  data() {
    return {
      // 筛选框的 form 表单
      isDisabled:false,
      form: {
        name: "",
        type: "",
        startTime:"",
        endTime:"",
        status:"",
        page: 1,
        limit: 20
      },
      tableKey: 0,
      list: [], // 表格数据
      total: 0, // 总条数
      listLoading: true, // 表格加载数据时的 loading
      importanceOptions: [
        {
            code:1,
            name:"单体贫血模型"
        },
        {
            code:2,
            name:"SOA贫血模型"
        },
        {
            code:3,
            name:"微服务贫血模型"
        },
      ], 
      templateLists:[],
      skeletonTemplate:[],
      calendarTypeOptions, // 类型的下拉选内容
      sortOptions: [
        {
            code:1,
            name:"已上线"
        },
        {
            code:2,
            name:"未上线"
        }], // 标题的下拉选
      statusOptions: ['published', 'draft', 'deleted'], // 新增和修改弹框里面的 Status 下拉框
      temp: { // 新增和修改弹框 的 form 表单
        name:"",
        type:"",
        codeGroupId:"",
        description:"",
        status:1,
        templateProjectId:""
      },
      rules: { // 表单验证
        name:[{ required: true, message: '请输入模板名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择模板类型', trigger: 'change' }],
        codeGroupId:[{ required: true, message: '请选择代码模板的分组', trigger: 'change' }],
        //templateProjectId:[{ required: true, message: '请选择项目骨架模板', trigger: 'change' }],
      },
      dialogFormVisible: false, // 弹框展示隐藏
      dialogStatus: '', // 弹框新增或者修改
      textMap: { // 弹框的标题
        update: '编辑',
        create: '新增'
      },
      downloadLoading: false, // 导出按钮 的 loading
      pickerOptions1:{
        disabledDate:time=>{
          if (this.form.endTime) {
            return time.getTime() > new Date(this.form.endTime).getTime()
          }
        }
      },
      pickerOptions2:{
        disabledDate:time=>{
          if (this.form.startTime) {
            return time.getTime() < new Date(this.form.startTime).getTime()- 86400000
          }
        }
      }
    }
  },
  async created() {
    await this.projectlist()
    this.getList()
    this.codeGrouplist()
    
  },
  methods: {
    // 获取表格数据
    getList() {
      this.listLoading = true
      projectTemplatefindPage(this.form).then(response => {
        this.list = response.data.list
        this.total = response.data.totalCount
        this.list.forEach(item=>{
          if(item.templateProjectId){
            const obj=this.skeletonTemplate.find(item1=>item1.id===item.templateProjectId)
            this.$set(item,"templateProjectName",obj?obj.name:"")
          }
          if(item.createTime){
             item.create_Time=parseTime(item.createTime)
          }
        })
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    async codeGrouplist(){
        const res=await codeGrouplist()
        if(res){
          this.templateLists=res.data
        }else{
            this.templateLists=[]
        }
    },
    async projectlist(){
        const res=await projectlist()
        if(res){
          this.skeletonTemplate=res.data
        }else{
            this.skeletonTemplate=[]
        }
    },
    handleLook(item){
        this.isDisabled=true
        this.dialogFormVisible=true
        this.$nextTick(()=>{
          this.$refs['dataForm'].resetFields()
          this.temp=JSON.parse(JSON.stringify(item))
        })
    },
    // 重新获取表格数据 页码归为1
    handleFilter() {
      this.form.page = 1
      this.getList()
    },
    handleReset(){
       this.form={
        name: "",
        type: "",
        startTime:"",
        endTime:"",
        status:"",
        page: 1,
        limit: 20,
       }
       this.getList()
    },
    // 新增数据-打开弹框
    handleCreate() {
      this.isDisabled=false
      this.dialogStatus = 'create'
      this.temp={
        name:"",
        type:"",
        codeGroupId:"",
        description:"",
        status:1,
        templateProjectId:""
      }
      this.dialogFormVisible = true
      this.$nextTick(()=>{
        this.$refs['dataForm'].resetFields()
      })
    },
    handleEdit(item){
      this.isDisabled=false
      this.dialogFormVisible = true
      this.dialogStatus = 'update'
      this.$nextTick(()=>{
        this.$refs['dataForm'].resetFields()
        this.temp=JSON.parse(JSON.stringify(item))
      })
    },
    // 新增数据-表单提交
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          projectTemplatesave(this.temp).then((res) => {
            if(res?.code===200){
              this.dialogFormVisible = false
              this.$message({
                //message: res.message,
                message: "新增成功",
                type: 'success',
              })
              this.getList()
            }
          })
        }
      })
    },
    // 修改 -- 提交表单
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          projectTemplateupdate(this.temp).then((res) => {
            this.dialogFormVisible = false
            this.$message({
              //message: res.message,
              message: "修改成功",
              type: 'success',
            })
            this.getList()
          })
        }
      })
    },
    async handleDelete(item){
      this.$confirm(`确定要进行删除操作?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(async () => {
            const res=await projectTemplatedelete(item.id)
            if(res){
              this.$message({
                  //message: res.message,
                  message: "删除成功",
                  type: 'success',
                })  
              this.getList()
            }
        })
    }
  }
}
</script>
<style lang="scss" scoped>
//表格布局的注释：
//$rowLength 这个变量表示了 筛选的搜索框会有多少行，由于在不同宽度显示器下 所占行数会不一定 ，所以下面使用媒体查询 做兼容
//最小兼容至 1366
@import '~@/styles/layout-table.scss';
$rowLength: 2;
@media all and (min-width: 1659px) {
    $rowLength: 2;
    @include calculation($rowLength: $rowLength);
}
@media all and (max-width: 1659px) {
    $rowLength: 3;
    @include calculation($rowLength: $rowLength);
}
</style>

<style>
.oneStyle{
  color: rgb(0, 0, 0);font-weight: 500;font-size: 14px;
}
.twoStyle{
  font-weight: 400;
    font-size: 12px;
    color: rgba(134,144,156,1);
}
.threeStyle{
  font-weight: 500;
    font-size: 12px;
    color: rgb(134, 144, 156);
}
</style>
